const path = require('path');
const dotenv = require('dotenv');

const { config: loadEnvConfig } = dotenv;

/** 一些目录路径参数 */
const ROOT_PATH = path.resolve(__dirname, '../../'); // 根路径
const SRC_PATH = path.resolve(ROOT_PATH, 'src'); // 源码路径
const DIST_PATH = path.resolve(ROOT_PATH, 'dist'); // 构建的结果路径
const PUBLIC_PATH = path.resolve(ROOT_PATH, 'public'); // public目录

/** 加载 env 属性 */
const ENV_CONFIG_PATH = path.resolve(ROOT_PATH, '.env');
loadEnvConfig({ path: ENV_CONFIG_PATH });

/** 获取 node env */
function getNodeEnv() {
  return process.env.NODE_ENV || 'dev';
}
const PRODUCTION = getNodeEnv() === 'prod';

/** 获取 CDN path */
function getCDNPath() {
  if (!PRODUCTION) return process.env.DEV_CDN_PATH || '/';
  if (process.env.CDN_PATH) return process.env.CDN_PATH;
  if (process.env.CDN_ROOT) {
    if (!process.env.USER_NAME || !process.env.PROJ_NAME) {
      console.log('USER_NAME or PROJ_NAME is undefined');
      console.log(`CDN_PATH 为默认值: '/'`);
    } else {
      return `${process.env.CDN_ROOT}/${process.env.USER_NAME}/${process.env.PROJ_NAME}`;
    }
  }
  return '/';
}

/** devServer 的代理 /api/* 的地址 */
const DEV_BACKEND_SERVER = process.env.DEV_BACKEND_SERVER;

/**
 * 这个数据用于 definePlugin 使用，用于作为全局变量在项目中使用
 * todo: 后续可能需要更新这里的数据
 */
const DEFINE_PLUGIN_ENV = {
  NODE_ENV: JSON.stringify(getNodeEnv()),
  CDN_PATH: JSON.stringify(
    PRODUCTION ? process.env.CDN_PATH || '/' : process.env.DEV_CDN_PATH || '/',
  ),
  BACKEND_SERVER: JSON.stringify(
    PRODUCTION ? process.env.BACKEND_SERVER : process.env.DEV_BACKEND_SERVER,
  ),
  SOCKET_SERVER: JSON.stringify(
    PRODUCTION ? process.env.SOCKET_SERVER : process.env.DEV_SOCKET_SERVER,
  ),
};

module.exports = {
  PRODUCTION,
  ROOT_PATH,
  SRC_PATH,
  DIST_PATH,
  PUBLIC_PATH,
  DEFINE_PLUGIN_ENV,
  DEV_BACKEND_SERVER,
  getNodeEnv,
  getCDNPath,
};
